package lesson03;

import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.ReentrantLock;

/**
 * lock.tryLock 设定时间内拿到了就执行，没拿到就自定义处理
 * new ReentrantLock(true); // 公平锁，新的线程进来后直接进队列等待，先到的先执行
 */
public class ReentrantLoock4 {

    ReentrantLock lock = new ReentrantLock();
    // ReentrantLock lock = new ReentrantLock(true); // 公平锁，新的线程进来后直接进队列等待，先到的先执行
    public void m1() {
        //
            try {
                lock.lock();
                System.out.println("m1....start ");
                for (int i = 0; i < 3 ; i++) {
                    TimeUnit.SECONDS.sleep(1);
                    System.out.println(i);
                }
                System.out.println("m1....end ");
            } catch (InterruptedException e) {
                e.printStackTrace();
            } finally {
                lock.unlock();
            }
        //}
    }

    /*
    synchronized void m2(){
        System.out.println("m2....");
    }
    */

    public void m2(){
        boolean islock = true;
        try {
            islock = lock.tryLock(5, TimeUnit.SECONDS);
            System.out.println("m2....islock: " + islock);
        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {
            if(islock) lock.unlock();
        }

    }

    public static void main(String[] args) {
        ReentrantLoock4 reeen = new ReentrantLoock4();
        Thread t1 = new Thread(reeen::m1);
        t1.start();

        new Thread(reeen::m2).start(); //

    }
}
